const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const app = getApp();

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * http请求
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'userToken': wx.getStorageSync('userToken')
      },
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 401){
            wx.setStorageSync('userInfo', null);
            wx.setStorageSync('userToken', null);
            app.globalData.hasLogin = false
            resolve(res.data);
          }else{
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

function uploadFile(url, filePath='') {
  return new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      header:{
        'userToken': wx.getStorageSync('userToken')
      },
      success(res) {
        resolve(res.data);
      }
    })
  });
}

module.exports = {
  formatTime: formatTime,
  request: request,
  uploadFile: uploadFile
}
